<?php

namespace App\Common;

use App\Models\CoinRecord;
use App\Models\Payment;
use App\Models\User;
use App\Support\Time;
use Illuminate\Support\Facades\DB;

class PaySuccess
{
    /**
     * 支付成功时的处理
     *
     * @param Payment $payment
     * @return bool
     */
    public function process(Payment $payment)
    {
        $result = DB::transaction(function () use ($payment) {
            // 已支付过的，不再处理
            if ($payment->isPaid()) {
                return true;
            }

            $payment->status = Payment::STATUS_PAID;
            $payment->paid_at = Time::now();
            $payment->save();

            $userId = $payment->user_id;

            // 生成游戏币记录
            $coin = $payment->payable;

            CoinRecord::create([
                'user_id' => $userId,
                'coin' => $coin->coin,
                'recordable_type' => CoinRecord::TYPE_PAYMENT,
                'recordable_id' => $payment->id,
            ]);

            if ($coin->coin_award > 0) {
                CoinRecord::create([
                    'user_id' => $userId,
                    'coin' => $coin->coin_award,
                    'recordable_type' => CoinRecord::TYPE_PAYMENT_AWARD,
                    'recordable_id' => $payment->id,
                ]);
            }

            // 给用户增加剩余游戏币、总的购买游戏币、总消费额
            $coins = $coin->coin + $coin->coin_award;
            User::where('id', $userId)->update([
                'coin' => DB::raw("coin + {$coins}"),
                'coin_buy' => DB::raw("coin_buy + {$coins}"),
                'cost_money' => DB::raw("cost_money + {$payment->money}"),
            ]);

            return true;
        });
        
        return $result;
    }
}
